package com.apes.project.jekunAuto.timeTask.product;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.project.jekunAuto.timeTask.BaseService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.product.model.*;
import com.apes.scm.masterdata.product.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName ContractSynService
 * @Description TODO
 * @Author pengyb
 * @Date 2020/1/9 11:21
 * @Version 1.0
 **/
@Service("productSynService")
public class ProductSynService extends BaseService {
    PiManager piManager;

    @Autowired
    void setPiManager(PiManager piManager) {
        this.piManager = piManager;
    }

    ProductGroupRepository productGroupRepository;

    @Autowired
    void setProductGroupRepository(ProductGroupRepository productGroupRepository) {
        this.productGroupRepository = productGroupRepository;
    }

    ClassifyRepository classifyRepository;

    @Autowired
    void setClassifyRepository(ClassifyRepository classifyRepository) {
        this.classifyRepository = classifyRepository;
    }

    TaxRepository taxRepository;

    @Autowired
    void setTaxRepository(TaxRepository taxRepository) {
        this.taxRepository = taxRepository;
    }

    BrandRepository brandRepository;

    @Autowired
    void setBrandRepository(BrandRepository brandRepository) {
        this.brandRepository = brandRepository;
    }

    ProductUomRepository productUomRepository;

    @Autowired
    void setProductUomRepository(ProductUomRepository productUomRepository) {
        this.productUomRepository = productUomRepository;
    }

    ProductUomCategoryRepository productUomCategoryRepository;

    @Autowired
    void setProductUomCategoryRepository(ProductUomCategoryRepository productUomCategoryRepository) {
        this.productUomCategoryRepository = productUomCategoryRepository;
    }

    ProductRepository productRepository;

    @Autowired
    void setProductRepository(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    CategoryRepository categoryRepository;

    @Autowired
    void setCategoryRepository(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    ServeCategoryRepository serveCategoryRepository;

    @Autowired
    void setServeCategoryRepository(ServeCategoryRepository serveCategoryRepository) {
        this.serveCategoryRepository = serveCategoryRepository;
    }

    ServeTypeRepository serveTypeRepository;

    @Autowired
    void setServeTypeRepository(ServeTypeRepository serveTypeRepository) {
        this.serveTypeRepository = serveTypeRepository;
    }

    EnumerationRepository enumerationRepository;

    @Autowired
    void setEnumerationRepository(EnumerationRepository enumerationRepository) {
        this.enumerationRepository = enumerationRepository;
    }

    ProductServiceHoursRepository productServiceHoursRepository;

    @Autowired
    void setProductServiceHoursRepository(ProductServiceHoursRepository productServiceHoursRepository) {
        this.productServiceHoursRepository = productServiceHoursRepository;
    }

    @Autowired
    private BrandTypeRepository brandTypeRepository;

    /**
     * 查询老系统商品数据
     *
     * @param request
     * @return
     */
    public JSONArray synProduct(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErpByConditions("mdmSpxxService.getProductList", "SPID");
        return objects;
    }

    /**
     * 查询老系统商品数据
     *
     * @param request
     * @return
     */
    public JSONArray synProductNew(SimpleRequest request) {
        while (true) {
            JSONObject resultObj = piManager.synErp("mdmSpxxService.getProductListNew", new JSONObject());
            JSONArray resultArray = JSONArray.parseArray(resultObj.getString("obj"));
            if (resultArray != null && resultArray.size() > 0) {
                for (Object o : resultArray) {
                    MQUtil.publish("product.syn.erp", "商品主数据保存", o);
                }
            }
            if((resultArray != null ? resultArray.size() : 0) < 2000){
                break;
            }
        }

        return null;
    }

    /**
     * 查询老系统商品分类信息
     *
     * @param request
     * @return
     */
    public JSONArray synProductClassify(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErpByConditions("mdmPlxxService.getClassifyList", "PLID");
        return objects;
    }

    /**
     * 查询老系统配件名称信息
     *
     * @param request
     * @return
     */
    public JSONArray synCategory(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErpByConditions("mdmPjmcService.getCategoryList", "PJMCID");
        return objects;
    }


    /**
     * 保存商品分类信息
     *
     * @param request
     * @return
     */
    public Classify saveProductClassify(SimpleRequest request) {
        JSONObject object = request.getJO();
        Classify classify = classifyRepository.findOne(object.getString("PLID"));
        if (classify == null) {
            classify = new Classify();
            classify.setId(object.getString("PLID"));
        }
        if (object.getString("SJID") != null) {
            Classify classifyRepositoryOne = classifyRepository.findOne(object.getString("SJID"));
            if (classifyRepositoryOne != null) {
                classify.setParents(classifyRepositoryOne);
            } else {
                recursion(object.getString("SJID"));
                classify.setParents(classifyRepository.findOne(object.getString("SJID")));
            }
        }
        classify.setName(object.getString("PLMC"));
        classify.setLastStage(object.getIntValue("MJBJ") != 0);
        classify.setLevels(object.getIntValue("JB"));
        classify.setValid(object.getIntValue("YXBJ") != 0);
        if (object.getString("SSLBID") != null) {
            Tax tax = taxRepository.findOne(JpaDsl.toCriteriaByEq("origin", object.getString("SSLBID"))).orElse(null);
            if (tax != null) {
                classify.setTax(tax);
            }
        }
        classify.getPath();
        Classify flush = classifyRepository.saveAndFlush(classify);
        //保存品类服务类型
        if (object.getString("FWLXID") != null) {
            ServeType serveType = new ServeType();
            serveType.setId(object.getString("FWLXID"));
            ServeCategory serveCategory = serveCategoryRepository.findOne(object.getString("PLID"));
            if (serveCategory == null) {
                serveCategory = new ServeCategory();
                serveCategory.setId(object.getString("PLID"));
            }
            serveCategory.setClassify(flush);
            serveCategory.setServeType(serveType);
            serveCategory.setStationType(enumerationRepository.findAll(JpaDsl.toCriteriaByEq("code", object.getString("GWLXID"), "type.id", "stationType")).stream().findFirst().orElse(null));
            serveCategoryRepository.saveAndFlush(serveCategory);
        }
        return flush;
    }

    /**
     * 递归保存分类信息
     *
     * @param SJID
     */
    public void recursion(String SJID) {
        //查询新框架父级
        Classify parents = classifyRepository.findOne(SJID);
        if (parents != null) {
            return;
        }
        JSONObject parseObject = piManager.synErp("mdmPlxxService.query", JSONObject.toJSONString(mapper("PLID", SJID)));
        JSONObject object = (JSONObject) (JSONArray.parseArray(parseObject.get("obj").toString())).stream().findAny().get();
        Classify classify = classifyRepository.findOne(object.getString("PLID"));
        if (object.getString("SJID") != null) {
            recursion(object.getString("SJID"));
        }
        if (classify == null) {
            classify = new Classify();
            classify.setId(object.getString("PLID"));
        }
        if (object.getString("SJID") != null) {
            classify.setParents(classifyRepository.findOne(object.getString("SJID")));
        }
        classify.setName(object.getString("PLMC"));
        classify.setLastStage(object.getIntValue("MJBJ") != 0);
        classify.setLevels(object.getIntValue("JB"));
        classify.setValid(object.getIntValue("YXBJ") != 0);
        if (object.getString("SSLBID") != null) {
            Tax tax = taxRepository.findOne(JpaDsl.toCriteriaByEq("origin", object.getString("SSLBID"))).orElse(null);
            if (tax != null) {
                classify.setTax(tax);
            }
        }
        classify.getPath();
        classifyRepository.saveAndFlush(classify);

    }

    /**
     * 保存商品信息
     *
     * @param request
     * @return
     */
    public Product saveProduct(SimpleRequest request) {
        Product product = request.getO(Product.class);
        JSONObject spxxInfoObj = piManager.synErp("ipmUtils.querySPXX", MapUtil.mapper("SPID", product.getId(), "newQuery", true));
        JSONArray returnData = JSONArray.parseArray(spxxInfoObj.get("obj").toString());
        if (returnData.size() == 0) throw new RuntimeException("未找到相关商品信息！");

        /**
         * 获取版本号
         */
        Product repositoryOne = productRepository.findOne(product.getId());
        if (null != repositoryOne) {
            product.setVersion(repositoryOne.getVersion());
        }
        request.setData(null);
        JSONObject requestJO = request.getJO();

        /**
         * 商品组
         */
        String productGroupId = requestJO.getString("SPZID");
        if (productGroupId != null) {
            ProductGroup productGroup = saveProductGroup(productGroupId, requestJO.getString("SPZMC"));
            product.setProductGroup(productGroup);
        }
        /**
         * 服务类型
         */
        //saveServeType(requestJO);

        /**
         * 商品分类
         */
        String plid = requestJO.getString("PLID");
        if (plid != null) {
            Classify productClassify = classifyRepository.findOne(plid);
            product.setClassify(productClassify);
            /**
             * 计量单位
             */
            String jldw = requestJO.getString("JLDW");
            Double factor = requestJO.getDouble("HSBL");
            if (jldw != null) {
                //根据计量单位名称和商品id(即计量单位id)查找
                ProductUom uom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("name", jldw, "uomCategory.id", product.getId())).stream().findFirst().orElse(null);
                if (uom == null) {
                    List<ProductUom> uoms = productUomRepository.findAll(JpaDsl.toCriteriaByEq( "uomCategory.id", product.getId())).stream().collect(Collectors.toList());
                    if (uoms.size() > 0) {
                        if (factor == 1) {
                            uom = uoms.stream().filter(u -> u.getFactor() == 1).findFirst().orElse(null);
                        } else {
                            uom = uoms.stream().filter(u -> Arith.round(1 / u.getFactor(), 2) == factor).findFirst().orElse(null);
                        }
                    }
                    if (uom == null) {
                        uom = new ProductUom();
                    }
                }
                uom.setName(jldw);
                uom.setFactor(factor == 1 ? factor : (factor > 1 ? 1 / factor : factor));
                BusinessAttributeValue value = new BusinessAttributeValue();
                value.setId(factor == 1 ? "ProductUom.uomType.reference" : (factor > 1 ? "ProductUom.uomType.bigger" : "ProductUom.uomType.smaller"));
                uom.setUomType(value);
                uom.setPurchaseFirst(requestJO.getBoolean("CGMRBJ"));
                uom.setSaleFirst(requestJO.getBoolean("XSMRBJ"));
                uom.setTransferFirst(requestJO.getBoolean("ZCMRBJ"));
                if (factor == 1) {
                    uom.setRounding((float) 0.0);
                } else {
                    uom.setRounding((float) 0.01);
                }
                ProductUomCategory productUomCategory = productUomCategoryRepository.findOne(product.getId());
                if (productUomCategory != null) {
                    productUomCategory.setName(product.getName());
                    productUomCategory.setClassify(productClassify);
                    productUomCategoryRepository.saveAndFlush(productUomCategory);
                    uom.setUomCategory(productUomCategory);

                } else {
                    ProductUomCategory uomCategory = new ProductUomCategory();
                    uomCategory.setId(product.getId());
                    uomCategory.setName(product.getName());
                    uomCategory.setClassify(productClassify);
                    uom.setUomCategory(productUomCategoryRepository.saveAndFlush(uomCategory));
                }
                ProductUom productUom = productUomRepository.saveAndFlush(uom);

                //比例为一 则赋值 否则赋值一个比例为一的单位
                if (factor == 1) {
                    product.setUom(productUom);
                } else {
                    product.setUom(productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", product.getId(), "factor", 1)).stream().findFirst().orElse(productUom));
                }

            }
        }

        /**
         * 配件名称
         */
        if (null != requestJO.getString("PJMCID")) {
            //调用配件名称同步方法
            product.setCategory(saveCategory(request));
        }
        /**
         * 品牌
         */
        String ppid = requestJO.getString("PPID");
        if (ppid != null) {
            product.setBrand(saveBrand(requestJO));
        }
        /**
         * 资产分类
         */
        String ZCFLID = requestJO.getString("ZCFLID");
        if (ZCFLID != null) {
            product.setFaCategory(SpringManager.getBean(FaCategoryRepository.class).findOne(ZCFLID));
        } else {
            product.setFaCategory(null);
        }

        /**
         * 税率
         */
        String sslbid = requestJO.getString("SSLBID");
        if (sslbid != null) {
            Optional<Tax> tax = taxRepository.findOne(JpaDsl.toCriteriaByEq("origin", sslbid));
            tax.ifPresent(product::setTax);
        }
        //('consu'：可消耗)，('aut'：服务)，('product'：可库存)
//        product.setType(requestJO.getIntValue("HYDWBJ") == 1 ? "consu" : ("10".
//                equals(productGroupId) ? "product" : ("20".
//                equals(productGroupId) ? "aut" : "")));

        Enumeration enumeration = enumerationRepository.findOne(requestJO.getString("ZDYBJ"));
        product.setCustomMarker(enumeration);
        product.setWorkerValid(requestJO.getIntValue("SGFS") == 1?true:false);
        product.setFreeSuppliesValid(requestJO.getBoolean("MFHCBJ"));
        product.setFreeServiceValid(requestJO.getBoolean("KSFWBJ"));
        product.setValid(requestJO.getIntValue("SPZT") == 0);
        product.setState(requestJO.getString("SPZT"));
        Double factor = requestJO.getDouble("HSBL");
        Product flush = productRepository.saveAndFlush(product);


        if (factor == 1) {
            String jldw = requestJO.getString("JLDW");
            List<ProductUom> uomList = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", product.getId(), "factor", 1));
            uomList.forEach(uom -> {
                if (!uom.getName().equals(jldw)) {
                    throw new RuntimeException("商品基本计量单位不允许变更！");
                }
            });
        }
        return flush;
    }

    // 老系统调用
    public Product saveProduct2(SimpleRequest request) {
        Product product = request.getO(Product.class);
        /**
         * 获取版本号
         */
        Product repositoryOne = productRepository.findOne(product.getId());
        if (null != repositoryOne) {
            product.setVersion(repositoryOne.getVersion());
        }
        request.setData(null);
        JSONObject requestJO = request.getJO();

        /**
         * 商品组
         */
        String productGroupId = requestJO.getString("SPZID");
        if (productGroupId != null) {
            ProductGroup productGroup = saveProductGroup(productGroupId, requestJO.getString("SPZMC"));
            product.setProductGroup(productGroup);
        }
        /**
         * 服务类型
         */
        //saveServeType(requestJO);

        /**
         * 商品分类
         */
        String plid = requestJO.getString("PLID");
        if (plid != null) {
            Classify productClassify = classifyRepository.findOne(plid);
            product.setClassify(productClassify);
            /**
             * 计量单位
             */
            String jldw = requestJO.getString("JLDW");
            Double factor = requestJO.getDouble("HSBL");
            if (jldw != null) {
                //根据计量单位名称和商品id(即计量单位id)查找
                ProductUom uom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("name", jldw, "uomCategory.id", product.getId())).stream().findFirst().orElse(null);
                if (uom == null) {
                    List<ProductUom> uoms = productUomRepository.findAll(JpaDsl.toCriteriaByEq( "uomCategory.id", product.getId())).stream().collect(Collectors.toList());
                    if (uoms.size() > 0) {
                        if (factor == 1) {
                            uom = uoms.stream().filter(u -> u.getFactor() == 1).findFirst().orElse(null);
                        } else {
                            uom = uoms.stream().filter(u -> Arith.round(1 / u.getFactor(), 2) == factor).findFirst().orElse(null);
                        }
                    }
                    if (uom == null) {
                        uom = new ProductUom();
                    }
                }
                uom.setName(jldw);
                uom.setFactor(factor == 1 ? factor : (factor > 1 ? 1 / factor : factor));
                BusinessAttributeValue value = new BusinessAttributeValue();
                value.setId(factor == 1 ? "ProductUom.uomType.reference" : (factor > 1 ? "ProductUom.uomType.bigger" : "ProductUom.uomType.smaller"));
                uom.setUomType(value);
                uom.setPurchaseFirst(requestJO.getBoolean("CGMRBJ"));
                uom.setSaleFirst(requestJO.getBoolean("XSMRBJ"));
                uom.setTransferFirst(requestJO.getBoolean("ZCMRBJ"));
                if (factor == 1) {
                    uom.setRounding((float) 0.0);
                } else {
                    uom.setRounding((float) 0.01);
                }
                ProductUomCategory productUomCategory = productUomCategoryRepository.findOne(product.getId());
                if (productUomCategory != null) {
                    productUomCategory.setName(product.getName());
                    productUomCategory.setClassify(productClassify);
                    productUomCategoryRepository.saveAndFlush(productUomCategory);
                    uom.setUomCategory(productUomCategory);

                } else {
                    ProductUomCategory uomCategory = new ProductUomCategory();
                    uomCategory.setId(product.getId());
                    uomCategory.setName(product.getName());
                    uomCategory.setClassify(productClassify);
                    uom.setUomCategory(productUomCategoryRepository.saveAndFlush(uomCategory));
                }
                ProductUom productUom = productUomRepository.saveAndFlush(uom);

                //比例为一 则赋值 否则赋值一个比例为一的单位
                if (factor == 1) {
                    product.setUom(productUom);
                } else {
                    product.setUom(productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", product.getId(), "factor", 1)).stream().findFirst().orElse(productUom));
                }

            }
        }

        /**
         * 配件名称
         */
        if (null != requestJO.getString("PJMCID")) {
            //调用配件名称同步方法
            Category category = categoryRepository.findOne(requestJO.getString("PJMCID"));
            if (category == null) {
                product.setCategory(saveCategory(request));
            } else {
                product.setCategory(category);
            }

        }
        /**
         * 品牌
         */
        String ppid = requestJO.getString("PPID");
        if (ppid != null) {
            product.setBrand(saveBrand(requestJO));
        }
        /**
         * 资产分类
         */
        String ZCFLID = requestJO.getString("ZCFLID");
        if (ZCFLID != null) {
            product.setFaCategory(SpringManager.getBean(FaCategoryRepository.class).findOne(ZCFLID));
        } else {
            product.setFaCategory(null);
        }

        /**
         * 税率
         */
        String sslbid = requestJO.getString("SSLBID");
        if (sslbid != null) {
            Optional<Tax> tax = taxRepository.findOne(JpaDsl.toCriteriaByEq("origin", sslbid));
            tax.ifPresent(product::setTax);
        }
        //('consu'：可消耗)，('aut'：服务)，('product'：可库存)
//        product.setType(requestJO.getIntValue("HYDWBJ") == 1 ? "consu" : ("10".
//                equals(productGroupId) ? "product" : ("20".
//                equals(productGroupId) ? "aut" : "")));

        Enumeration enumeration = enumerationRepository.findOne(requestJO.getString("ZDYBJ"));
        product.setCustomMarker(enumeration);
        product.setFreeSuppliesValid(requestJO.getBoolean("MFHCBJ"));
        product.setFreeServiceValid(requestJO.getBoolean("KSFWBJ"));
        product.setValid(requestJO.getIntValue("SPZT") == 0);
        product.setState(requestJO.getString("SPZT"));
        Double factor = requestJO.getDouble("HSBL");
        Product flush = productRepository.saveAndFlush(product);
        if (factor == 1) {
            String jldw = requestJO.getString("JLDW");
            List<ProductUom> uomList = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", product.getId(), "factor", 1));
            uomList.forEach(uom -> {
                if (!uom.getName().equals(jldw)) {
                    uom.setValid(false);
//                    productUomRepository.delete(uom);
                }
            });
            productUomRepository.saveAll(uomList);
        }
        return flush;
    }

    /**
     * 保存类目信息
     *
     * @param request
     * @return
     */
    public Category saveCategory(SimpleRequest request) {
        JSONObject object = request.getJO();
        Category category = categoryRepository.findOne(object.getString("PJMCID"));
        if (category == null) {
            category = new Category();
            category = getCategory(object, category);
        } else {
//            if (!category.getName().equals(object.getString("PJMC")) || !category.getClassify().getId().equals(object.getString("PLID"))) {
                category = getCategory(object, category);
//            }
        }

        return category;
    }

    public void test(SimpleRequest request){
        Category category = categoryRepository.findOne("000615");
        invoke("product.spCategoryService.saveCategory", MapUtil.mapped(category));
    }

    public Category getCategory(JSONObject object, Category category) {
        category.setId(object.getString("PJMCID"));
        category.setName(object.getString("PJMC"));
        Classify plid = classifyRepository.findOne(object.getString("PLID"));
        category.setClassify(plid);
        if (object.getString("PPYSBJ") != null) {
            category.setMatchColor(object.getBoolean("PPYSBJ"));
        }
        if (object.getString("PPSPBJ") != null) {
            category.setMatchCProduct(object.getBoolean("PPSPBJ"));
        }
        category.setCategoryPhotos(object.getString("TPLJ"));
        category = categoryRepository.saveAndFlush(category);
        return category;
    }

    public void saveServeType(JSONObject requestJO) {
        if (requestJO.getString("SPFWLXID") != null) {
            ServeType serveType = serveTypeRepository.findOne(requestJO.getString("SPFWLXID"));
            if (serveType == null) {
                serveType = new ServeType();
                serveType.setId(requestJO.getString("SPFWLXID"));
            }
            serveType.setName(requestJO.getString("SPFWLXMC"));
            serveType.setSuperiorId(requestJO.getString("FWSJID"));
            serveTypeRepository.saveAndFlush(serveType);
        }
    }

    public ProductGroup saveProductGroup(String productGroupId, String productGroupName) {
        ProductGroup productGroup = productGroupRepository.findOne(productGroupId);
        if (productGroup == null) {
            productGroup = new ProductGroup();
            productGroup.setId(productGroupId);
        }
        if (!"一般商品".equals(productGroupName))productGroup.setName(productGroupName);
        return productGroupRepository.saveAndFlush(productGroup);
    }

    public Classify saveClassify(SimpleRequest requestJO) {
        Classify productClassify = saveProductClassify(requestJO);
        return productClassify;
    }

    public Brand saveBrand(JSONObject requestJO) {
        Brand brand = brandRepository.findOne(requestJO.getString("PPID"));
        if (brand == null) {
            brand = new Brand();
            brand.setId(requestJO.getString("PPID"));
        }
        brand.setName(requestJO.getString("PPMC"));
        brand.setEnName(requestJO.getString("YWMC"));
        if (requestJO.getString("PPLXID") != null) {
            BrandType pplxid = brandTypeRepository.findOne(requestJO.getString("PPLXID"));
            if (pplxid==null){
                BrandType type = new BrandType();
                type.setId(requestJO.getString("PPLXID"));
                type.setName(requestJO.getString("PPLXMC")==null?"未知品牌类型":requestJO.getString("PPLXMC"));
                pplxid = brandTypeRepository.saveAndFlush(type);
            }

            brand.setBrandType(pplxid);
        }
        if (requestJO.getString("PZID") != null) {
            Enumeration character = SpringManager.getBean(EnumerationRepository.class).findByTypeAndCode("qualityType", requestJO.getString("PZID"));
            brand.setCharacter(character);
        }
        if (requestJO.getString("XFPZID") != null) {
            Enumeration subQuality = SpringManager.getBean(EnumerationRepository.class).findByTypeAndCode("subQuality", requestJO.getString("XFPZID"));
            brand.setSubQuality(subQuality);
        }

        return brandRepository.saveAndFlush(brand);
    }

    /**
     * 同步商品服务工时（查询）
     *
     * @param request
     * @return
     */
    public JSONArray synProductServiceHours(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErp("mdmSpfwgsService.getProductServiceHours");
        return objects;
    }

    /**
     * 同步商品服务工时（保存）
     *
     * @param request
     * @return
     */
    public ProductServiceHours saveProductServiceHours(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String productId = requestJO.getString("SPID");
        ProductServiceHours serviceHours = productServiceHoursRepository.findOne(productId);
        if (serviceHours == null) {
            serviceHours = new ProductServiceHours();
            serviceHours.setId(productId);
        }
        serviceHours.setProduct(productRepository.findOne(productId));
        serviceHours.setServiceHours(requestJO.getInteger("SGSC"));
        serviceHours.setValid(requestJO.getBoolean("YXBJ"));
        return productServiceHoursRepository.saveAndFlush(serviceHours);
    }

    /**
     * 计量单位不一致同步
     */
    public void synDifferentProductUom() {
        JSONObject getData = piManager.synErp("mdmSpxxService.queryDifferentJLDW", new JSONObject());
        JSONArray jldwInfo = JSONArray.parseArray(getData.get("obj").toString());
        jldwInfo.forEach(singleObj -> {
            JSONObject singleJLDW = (JSONObject) singleObj;
            if (singleJLDW.getIntValue("OLD_UOM_COUNT") == 1) { // 老系统只有一个计量单位直接修改
                List<ProductUom> productUomList = productUomRepository.findAll(JpaDsl.toCriteriaByEq(/*"name", singleJLDW.getString("NAME"),*/ "uomCategory.id", singleJLDW.getString("SPID")));
                ProductUom productUom = productUomList.get(0);
                productUom.setName(singleJLDW.getString("JLDW"));
                productUomRepository.save(productUom);
            } else {
                ProductUom uom = this.appendUomData(singleJLDW);
                productUomRepository.save(uom);
            }
        });
    }

    // 拼接计量单位
    private ProductUom appendUomData(JSONObject jldwObj) {
        double hsbl = jldwObj.getDoubleValue("HSBL");
        ProductUom uom = new ProductUom();
        uom.setName(jldwObj.getString("JLDW"));
        uom.setValid(true);
        uom.setFactor(1 / hsbl);
        uom.setRounding(0.01);
        if (hsbl > 1) {
            uom.setUomType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ProductUom.uomType.bigger"));
        } else {
            uom.setUomType(SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ProductUom.uomType.reference"));
        }
        uom.setUomCategory(SpringManager.getBean(ProductUomCategoryRepository.class).findOne(jldwObj.getString("SPID")));
        uom.setPurchaseFirst(jldwObj.getIntValue("CGMRBJ") == 1?true:false);
        uom.setSaleFirst(jldwObj.getIntValue("XSMRBJ") == 1?true:false);
        uom.setTransferFirst(jldwObj.getIntValue("ZCMRBJ") == 1?true:false);
        return uom;
    }


    /**
     * 商品品牌同步
     */
    public void synProductBrand(SimpleRequest request) {
        JSONArray objects = piManager.timedTaskSynErpByConditions("mdmPpxxService.getPpxxList", "PPID");
        invoke("product.spBrandService.saveBrand", MapUtil.mapper("data", objects));
        for (Object object : objects) {
            JSONObject ppxx = (JSONObject) object;
            saveBrand(ppxx);
        }
    }

}
